/*
 */
package aptech.eproject.logictics.dao.kien;

import aptech.eproject.logictics.db.Account;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Kien Nguyen <solidfoxrock at gmail.com>
 */
@Stateless
public class AccountService implements AccountServiceRemote {

    @PersistenceContext
    private EntityManager em;

    /**
     *
     * @return
     */
    @Override
    public List<Account> findAccounts() {
        Query q = em.createNamedQuery("findAccounts");
        return q.getResultList();
    }

    /**
     *
     * @param userName
     * @return
     */
    @Override
    public Account findAccount(String userName) {
        return em.find(Account.class, userName);
    }

    /**
     *
     * @param fullName
     * @return
     */
    @Override
    public List<Account> findAccountsByFullName(String fullName) {
        Query q = em.createNamedQuery("findAccountsByFullName");
        q.setParameter(1, "%" + fullName + "%");
        List<Account> results = q.getResultList();
        return results;
    }

    /**
     *
     * @param account
     */
    @Override
    public void create(Account account) {
        em.persist(account);
    }

    /**
     *
     * @param account
     */
    @Override
    public void edit(Account account) {
        if (account.getBranch() != null) {
            em.merge(account.getBranch());
        }
        em.merge(account);
    }

    /**
     *
     * @param userName
     */
    @Override
    public void block(String userName) {
        Account account = em.find(Account.class, userName);
        if (account == null) {
            throw new EntityNotFoundException("The account with id " + userName + " does not exist");
        }
        account.setIsBlocked(true);
        em.merge(account);
    }

    /**
     *
     * @param userName
     */
    @Override
    public void unblock(String userName) {
        Account account = em.find(Account.class, userName);
        if (account == null) {
            throw new EntityNotFoundException("The account with id " + userName + " does not exist");
        }
        account.setIsBlocked(false);
        em.merge(account);
    }

    /**
     * for testing only
     * @param userName
     */
    @Override
    public void removeForever(String userName) {
        Account account = em.find(Account.class, userName);
        if (account != null) {
            em.remove(account);
        }
    }
}
